<template>
  <div class="logistics-page">
    <!-- 页面标题 -->
    <div class="page-header bg-white border-b border-gray-200">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center">
          <el-button @click="router.back()" text>
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <h1 class="text-2xl font-bold text-gray-900 ml-4">物流跟踪</h1>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <!-- 物流信息卡片 -->
      <div class="logistics-card">
        <div class="card-header">
          <div class="delivery-info">
            <div class="company">
              <span class="label">物流公司：</span>
              <span class="value">{{ logistics.company }}</span>
            </div>
            <div class="tracking-number">
              <span class="label">物流单号：</span>
              <span class="value">{{ logistics.trackingNumber }}</span>
              <el-button type="primary" link @click="copyTrackingNumber">
                复制单号
              </el-button>
            </div>
          </div>
          <div class="status-info">
            <el-tag :type="getStatusType(logistics.status)">
              {{ getStatusText(logistics.status) }}
            </el-tag>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="delivery-address">
          <div class="address-card">
            <div class="icon">
              <el-icon><Location /></el-icon>
            </div>
            <div class="content">
              <div class="title">收货地址</div>
              <div class="address">
                <p>
                  {{ logistics.receiverName }} {{ logistics.receiverPhone }}
                </p>
                <p>{{ logistics.receiverAddress }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 包裹信息 -->
        <div class="package-info">
          <div class="package-items">
            <div
              v-for="item in logistics.items"
              :key="item.id"
              class="package-item"
            >
              <el-image
                :src="item.image"
                :alt="item.name"
                class="item-image"
                fit="cover"
              />
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-specs">{{ item.specs }}</div>
                <div class="item-quantity">x{{ item.quantity }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 物流轨迹 -->
      <div class="logistics-timeline">
        <div class="timeline-header">
          <h2 class="text-lg font-medium">物流轨迹</h2>
          <el-button type="primary" link @click="refreshTracking">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>

        <div class="timeline-content">
          <el-timeline>
            <el-timeline-item
              v-for="(track, index) in logistics.tracks"
              :key="index"
              :type="getTrackType(track, index)"
              :hollow="index !== 0"
              :timestamp="track.time"
            >
              <div class="track-info">
                <div class="track-status">{{ track.status }}</div>
                <div class="track-location">{{ track.location }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <!-- 温馨提示 -->
      <div class="tips-section">
        <el-alert title="温馨提示" type="info" :closable="false" show-icon>
          <div class="tips-content">
            <p>1. 如遇快递延迟，可联系快递公司或客服处理</p>
            <p>2. 如需修改收货地址，请尽快联系客服</p>
            <p>3. 收货前请仔细检查包裹，如有问题及时反馈</p>
          </div>
        </el-alert>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft, Location, Refresh } from "@element-plus/icons-vue";
import axios from "@/api/axios";

const router = useRouter();
const route = useRoute();
const orderId = route.params.id;
const loading = ref(true);

// 物流信息
const logistics = ref({
  company: "顺丰速运",
  trackingNumber: "SF1234567890123",
  status: "in_transit",
  receiverName: "张三",
  receiverPhone: "138****8888",
  receiverAddress: "广西壮族自治区贵港市港北区贵港大道123号",
  items: [
    {
      id: 1,
      name: "贵港特色手工艺品",
      specs: "规格：标准款",
      quantity: 1,
      image: "/images/products/product1.jpg",
    },
  ],
  tracks: [
    {
      time: "2024-03-18 10:30:00",
      status: "快件已签收",
      location: "广西贵港市港北区",
    },
    {
      time: "2024-03-18 09:15:00",
      status: "快件已到达【贵港港北营业点】",
      location: "广西贵港市港北区",
    },
    {
      time: "2024-03-18 07:30:00",
      status: "快件在【贵港转运中心】完成分拣",
      location: "广西贵港市",
    },
    {
      time: "2024-03-17 20:45:00",
      status: "快件已到达【贵港转运中心】",
      location: "广西贵港市",
    },
    {
      time: "2024-03-17 18:20:00",
      status: "快件已发出",
      location: "广西南宁市",
    },
    {
      time: "2024-03-17 16:30:00",
      status: "商家已发货",
      location: "广西南宁市",
    },
  ],
});

// 获取物流状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: "info",
    in_transit: "primary",
    delivered: "success",
    exception: "danger",
  };
  return typeMap[status] || "info";
};

// 获取物流状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: "待发货",
    in_transit: "运输中",
    delivered: "已签收",
    exception: "异常",
  };
  return textMap[status] || "未知状态";
};

// 获取轨迹节点类型
const getTrackType = (track, index) => {
  if (index === 0) {
    return "primary";
  }
  if (track.status.includes("异常")) {
    return "danger";
  }
  return "";
};

// 复制物流单号
const copyTrackingNumber = async () => {
  try {
    await navigator.clipboard.writeText(logistics.value.trackingNumber);
    ElMessage.success("物流单号已复制");
  } catch (error) {
    console.error("复制失败:", error);
    ElMessage.error("复制失败");
  }
};

// 刷新物流轨迹
const refreshTracking = async () => {
  try {
    loading.value = true;
    await getLogistics();
    ElMessage.success("物流信息已更新");
  } catch (error) {
    console.error("更新物流信息失败:", error);
    ElMessage.error("更新物流信息失败");
  } finally {
    loading.value = false;
  }
};

// 获取物流信息
const getLogistics = async () => {
  try {
    loading.value = true;
    
    // 调用获取物流信息API
    try {
      const response = await axios.get(`/orders/${orderId}/logistics`);
      
      if (response) {
        logistics.value = response;
        return;
      }
    } catch (error) {
      console.error("获取物流信息API失败:", error);
      // 使用测试数据
    }
    
    // 使用测试数据 - 保持原有测试数据不变
  } catch (error) {
    console.error("获取物流信息失败:", error);
    ElMessage.error("获取物流信息失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getLogistics();
});
</script>

<style lang="scss" scoped>
.logistics-page {
  .logistics-card {
    @apply bg-white rounded-lg overflow-hidden mb-6;

    .card-header {
      @apply flex items-center justify-between p-6 border-b border-gray-100;

      .delivery-info {
        @apply space-y-2;

        .company,
        .tracking-number {
          @apply flex items-center;

          .label {
            @apply text-gray-500;
          }

          .value {
            @apply text-gray-900 ml-2;
          }
        }
      }
    }

    .delivery-address {
      @apply p-6 border-b border-gray-100;

      .address-card {
        @apply flex items-start;

        .icon {
          @apply mr-4 text-primary-600 text-xl;
        }

        .content {
          @apply flex-1;

          .title {
            @apply text-gray-500 mb-2;
          }

          .address {
            @apply text-gray-900 space-y-1;
          }
        }
      }
    }

    .package-info {
      @apply p-6;

      .package-items {
        @apply space-y-4;

        .package-item {
          @apply flex items-start;

          .item-image {
            @apply w-16 h-16 rounded;
          }

          .item-info {
            @apply flex-1 ml-4;

            .item-name {
              @apply text-gray-900 font-medium mb-1;
            }

            .item-specs {
              @apply text-sm text-gray-500 mb-1;
            }

            .item-quantity {
              @apply text-sm text-gray-500;
            }
          }
        }
      }
    }
  }

  .logistics-timeline {
    @apply bg-white rounded-lg p-6;

    .timeline-header {
      @apply flex items-center justify-between mb-6;
    }

    .timeline-content {
      :deep(.el-timeline-item__content) {
        .track-info {
          @apply mb-2;

          .track-status {
            @apply text-gray-900 font-medium mb-1;
          }

          .track-location {
            @apply text-sm text-gray-500;
          }
        }
      }

      :deep(.el-timeline-item__timestamp) {
        @apply text-sm text-gray-400;
      }
    }
  }

  .tips-section {
    @apply mt-6;

    .tips-content {
      @apply text-sm space-y-1;
    }
  }
}
</style>
